using System;
using System.Linq;
using System.Xml.Linq;

namespace TicTacToe.Net
{
    sealed class NetMessage
    {
        public readonly DateTime Timestamp;
        public readonly string Header;
        public readonly XElement Content;

        public string Serialize()
        {
            return new XElement("netmessage",
                new XElement("timestamp", Timestamp),
                new XElement("header", Header),
                new XElement("content", Content)).ToString();
        }

        public static NetMessage Deserialize(string data)
        {
            var obj = XElement.Parse(data);
            var header = obj.Element("header").Value;
            var timestamp = DateTime.Parse(obj.Element("timestamp").Value);
            var content = obj.Element("content").Elements().Single();

            return new NetMessage(header, timestamp, content);
        }

        public override string ToString()
        {
            return Serialize();
        }

        public NetMessage(string header, XElement content)
        {
            Header = header;
            Timestamp = DateTime.Now;
            Content = content;
        }

        private NetMessage(string header, DateTime timestamp, XElement content)
        {
            Header = header;
            Timestamp = timestamp;
            Content = content;
        }
    }
}